<template>
  <div class="goods">
    <div class="menu-wrapper" ref="menuwrapper">
      <ul>
        <li v-for="(item, index) in goods" v-bind:key="index" class="menu-item border-1px" :class="{'current':currentIndex===index}" @click="seletMenu(index,$event)">
          <span class="text">
            <span v-if="item.type > 0"><icon :type="item.type" size="3"></icon></span>
            {{item.name}}
          </span>
        </li>
      </ul>
    </div>
    <div class="foods-wrapper" ref="foodswrapper">
      <ul>
        <li v-for="(item, index) in goods" v-bind:key="index" class="food-list food-list-hook">
          <h1 class="title">{{item.name}}</h1>
          <ul>
            <li v-for="(food, indexfood) in item.foods" v-bind:key="indexfood" class="food-item border-1px" @click="selectFood(food, $event)">
              <div class="icon">
                <img width="57" height="57" :src="food.icon" />
              </div>
              <div class="content">
                <h2 class="name" >{{food.name}}</h2>
                <p class="desc">{{food.description}}</p>
                <div class="extra">
                  <span class="count">月售{{food.sellCount}}份</span><span>好评率{{food.rating}}%</span>
                </div>
                <div class="price">
                  <span class="now">￥{{food.price}}</span>
                  <span v-show="food.oldPrice" class="old">￥{{food.oldPrice}}</span>
                </div>
                <div class="cartcontrol-wrapper" > <!--需要给组件定位，所有先给外面一个wrapper-->
                  <!-- <cartcontrol :food="food" @cart-add="cartAdd"></cartcontrol> -->
                  <cartcontrol :food="food"></cartcontrol>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <shopcart ref="shopcart" :select-foods="selectFoods" :delivery-price="seller.deliveryPrice" :min-price="seller.minPrice" @clear-selectfoods="clearSelectFoods" >
    </shopcart>
    <food ref="food" :food="selectedFood" @cart-add="cartAdd"></food>
  </div>
</template>

<script type="text/ecmascript-6">
import Vue from 'vue'
import BScroll from 'better-scroll'
import icon from '../../components/commcomp/icon/icon'
import shopcart from '../../components/shopcart/shopcart'
import cartcontrol from '../../components/cartcontrol/cartcontrol'
import food from '../../components/food/food'
import bus from '../../assets/eventBus'

const ERR_OK = 0

export default {
  props: {
    seller: {
      type: Object,
    },
  },
  components: {
    icon,
    shopcart,
    cartcontrol,
    food,
  },
  data() {
    return {
      // goods: [],
      listHeight: [],
      scrollY: 0,
      selectedFood: {},
    }
  },
  created() {
    this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee']

    // this.$http.get('/api/goods', { emulateJSON: true }).then((response) => {
    //   if (response.data.errno === ERR_OK) {
    //     this.goods = response.data.data
    //     this.$nextTick(() => {
    //       // DOM 现在更新了
    //       // `this` 绑定到当前实例
    //       this.initScroll()
    //       this.calculateHeight()
    //     })
    //   }
    // }, () => {
    //   console.log('服务器错误！')
    // })

    this.$store.dispatch('goods/initGoods', {}).then(() => {
      this.$nextTick(() => {
        // DOM 现在更新了
        this.initScroll() // `this` 绑定到当前实例
        this.calculateHeight()
      })
    }, (err) => {
      console.log('err')
    })
  },
  methods: {
    initScroll() {
      this.menuScroll = new BScroll(this.$refs.menuwrapper, {
        click: true,
      })
      this.foodsScroll = new BScroll(this.$refs.foodswrapper, {
        probeType: 3,
        click: true,
      })
      this.foodsScroll.on('scroll', (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y))
      })
    },
    calculateHeight() { // DOM 创建完成后，计算每个food-list的高度，并存入数组listHeight中
      const foodsWrapper = this.$refs.foodswrapper
      const foodList = foodsWrapper.getElementsByClassName('food-list-hook')
      let height = 0
      this.listHeight.push(height)
      for (let i = 0; i < foodList.length; i++) {
        height += foodList[i].clientHeight
        this.listHeight.push(height)
      }
    },
    seletMenu(index, event) {
      if (!event._constructed) {
        return
      }
      const foodsWrapper = this.$refs.foodswrapper
      const foodList = foodsWrapper.getElementsByClassName('food-list-hook')
      const el = foodList[index]
      this.foodsScroll.scrollToElement(el, 500)
    },
    cartAdd(elTarget) {
      this.$refs.shopcart.dropBall(elTarget)
    },
    clearSelectFoods() {
      // this.goods.forEach((good) => {
      //   good.foods.forEach((tfood) => {
      //     if (tfood.count > 0) {
      //       Vue.set(tfood, 'count', 0)
      //     }
      //   })
      // })
      this.$store.commit('goods/clearSelectFoods')
      this.$refs.shopcart.fold = false
    },
    selectFood(selectedfood, event) {
      if (!event._constructed) {
        return
      }
      this.selectedFood = selectedfood
      this.$refs.food.show()
    },
  },
  computed: {
    goods() {
      return this.$store.state.goods.data
    },
    currentIndex() {
      for (let i = 0; i < this.listHeight.length; i++) {
        const height1 = this.listHeight[i]
        const height2 = this.listHeight[i + 1]
        if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
          return i
        }
      }
      return 0
    },
    selectFoods() {
      const selectfoods = []
      this.goods.forEach((tgood) => {
        tgood.foods.forEach((tfood) => {
          if (tfood.count) {
            selectfoods.push(tfood)
          }
        })
      })
      return selectfoods
    },
  },
  mounted() {
    bus.$on('cartcontrol/addCart', (elTarget) => {
      // console.log('elTarget')
      // console.log(elTarget)
      this.$refs.shopcart.dropBall(elTarget)
    })
  },
  // watch: {
  //   goods() {
  //     this.$nextTick(() => {
  //       console.log('goods/initGoods nextTick')
  //       // DOM 现在更新了
  //       this.initScroll() // `this` 绑定到当前实例
  //       this.calculateHeight()
  //     })
  //   }
  // }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" rel="stylesheet/stylus">

  @import "../../common/stylus/mixin"

  .goods
    display: flex
    position: absolute // 父级没有positon，一直往上找，最后找到<html>作为绝对定位的起始
    top: 174px
    bottom: 46px
    width: 100%
    overflow: hidden
    .menu-wrapper
      flex: 0 0 80px  // flex-grow, flex-shrink, flex-basis
      width: 80px
      background: #f3f5f7
      .menu-item
        display: table
        padding: 0 12px
        height: 54px
        width: 56px
        line-height: 14px
        &.current
          position: relative
          z-index: 10
          margin-top: -1px
          font-weight: 700
          background: #fff
          .text
            border-none()
        .text
          display: table-cell
          width: 56px
          vertical-align: middle
          border-1px(rgba(7,17,27,0.1))
          font-size: 12px
          .icon
            margin-right: 2px
    .foods-wrapper
      flex: 1
      .title
        padding-left: 14px
        height: 26px
        line-height: 26px
        border-left: 2px solid #d9dde1
        font-size: 12px
        color: rgb(147, 153, 159)
        background: #f3f5f7
      .food-item
        display: flex
        margin: 18px
        padding-bottom: 18px
        border-1px(rgba(7,17,27,0.1))
        &:last-child
          border-none()
          margin-bottom: 18px
        .icon
          flex: 0 0 57px
          margin-right: 10px
        .content
          flex: 1
          .name
            margin: 2px 0 8px 0
            height: 14px
            line-height: 14px
            color: rgb(7,17,27)
          .desc, .extra
            line-height: 12px
            color: rgb(147, 153, 159)
            font-size: 10px
          .desc
            margin-bottom: 8px
          .extra
            .count
              margin-right: 12px
          .price
            font-weight: 700
            line-height: 24px
            .now
              margin-right: 8px
              font-size: 14px
              color: rgb(240, 20, 20)
              vertical-align: top
            .old
              text-decoration: line-through
              font-size: 10px
              color: rgb(147, 153, 159)
          .cartcontrol-wrapper
            position: absolute
            right: 0
            bottom: 12px
</style>
